<template>
  <AreaListPopWindow ref="popWindow" title="省市区选择" sizeType="large" :btnType="2" @success="closeWin">
    <div class="regionBox">
      <MyAreaList :defaultItem="areaListData" :dataAll="areaListData" :titleType="titleType" />
    </div>
  </AreaListPopWindow>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import MyAreaList from "./MyAreaList.vue";
import { ElMessage } from "element-plus";
import { areaData } from "@/utils/location";
import AreaListPopWindow from "./AreaListPopWindow.vue";
import { tr } from "element-plus/es/locale";

const Props: any = defineProps({
  popWindowDisable: {
    type: Boolean,
    required: true,
    default: false,
  },
  // chosedData: {
  //   type: Array,
  //   default: [],
  // },
  defaultItex: {
    type: Number,
    default: 0,
  },
  defaultTitle: {
    type: String,
    default: "",
  },
  defaultItem: {
    type: Array,
    default() {
      return []
    }
  },
});
const emit = defineEmits(["regionBack"]);
// watch(
// () => Props.dialogVisible,
// (n: any) => {
//   if (n) {
//     areaListData.value = [];
//     areaListData.value = dataChange(JSON.parse(JSON.stringify(areaData)), 0);
//     if (Props.defaultItem.length > 0) {
//       checkChosedData(Props.defaultItem, areaListData.value);
//       console.log(areaListData)
//     }
//   }
// }
// );
const areaListData: any = ref([]);
const dataChange = (arr: any, count: any) => {
  arr.length > 0 &&
    arr.map((item: any) => {
      item.chosedArr = [];
      item.isIndeterminate = false;
      item.checkAll = false;
      item.isShow = count > 0 ? false : true;
      item.titleType = count;
      item.titleClass = "titleClass" + count;
      item.allArr = [];
      item.allName = "";
      if (item.childrenList && item.childrenList.length > 0) {
        item.childrenList.map((child: any) => {
          item.allArr.push(child.coding);
          item.allName = item.allName + (item.allName ? "、" : "") + child.areaName;
        });
        dataChange(item.childrenList, count + 1);
      }
    });
  return arr;
};

const findParent = (list: any, parentId: any) => {
  list.forEach((result: any) => {
    let parentCheckedLength = 0;
    let parentIndeterminateLength = 0;
    if (result.coding === parentId) {
      result.chosedArr = [];
      result.childrenList.forEach((item: any) => {
        if (item.isIndeterminate) {
          parentIndeterminateLength++;
        } else if (item.checkAll) {
          parentCheckedLength++;
          result.chosedArr.push(item.coding);
        }
      });
      result.checkAll = parentCheckedLength === result.allArr.length;
      result.isIndeterminate = (parentIndeterminateLength > 0 || parentCheckedLength > 0) && parentCheckedLength < result.allArr.length;
      if (result.parentId !== 0) {
        findParent(areaListData.value, result.parentId);
      }
    } else if (result.childrenList.length > 0) {
      findParent(result.childrenList, parentId);
    }
  });
};
const closeWin = (e: any) => {
  let obj: any = {
    name: "",
    codIngList: [],
  };
  if (e) {
    getChosedData(areaListData.value, obj);
    if (obj.codIngList.length == 0) {
      ElMessage({
        type: "error",
        message: "请先选择一个区域",
      });
      return;
    }
    console.log(obj)
    emit("regionBack", obj, Props.defaultItex, Props.defaultTitle);
    areaListData.value = [];
  } else {
    emit("regionBack", obj, Props.defaultItex, Props.defaultTitle);
  }

};
const getChosedData = (arr: any, obj: any) => {
  for (let i = 0, len = arr.length; i < len; i++) {
    let item = arr[i];
    console.log(item)
    // if (item.isIndeterminate && item.chosedArr.length > 0) {
    //   obj.codIngList = [...obj.codIngList, ...item.chosedArr];
    //   item.chosedArr.map((options: any) => {
    //     item.childrenList.map((op: any) => {
    //       if (options == op.coding) {
    //         obj.name = obj.name + (obj.name ? "、" : "") + op.areaName;
    //         obj.codIngList = [...obj.codIngList, ...op.chosedArr];
    //         // op.chosedArr.map((kItem: any) => {
    //         //   op.childrenList.map((kOptions: any) => {
    //         //     if (kItem == kOptions.coding) {
    //         //       obj.name = obj.name + (obj.name ? "、" : "") + kOptions.areaName;
    //         //     }
    //         //   })
    //         // })
    //       }
    //     });
    //   });
    //   continue
    // }
    if (item.chosedArr.length > 0) {

      obj.codIngList = [...obj.codIngList, ...item.chosedArr];

      item.chosedArr.map((options: any) => {
        item.childrenList.map((op: any) => {
          if (options == op.coding) {
            console.log("op.areaName=" + op.areaName)
            obj.name = obj.name + (obj.name ? "、" : "") + op.areaName;
            if (!op.checkAll) {
              obj.codIngList = [...obj.codIngList, ...op.chosedArr];
              op.chosedArr.map((kItem: any) => {
                op.childrenList.map((kOptions: any) => {
                  if (kItem == kOptions.coding) {
                    console.log("kOptions.areaName=" + kOptions.areaName)
                    obj.name = obj.name + (obj.name ? "、" : "") + kOptions.areaName;
                  }
                })
              })
            }
          }
        });
      });
      continue
    }
    if (item.isIndeterminate) {
      getChosedData(item.childrenList, obj)
      continue
    }
  }
};

const checkChosedData = (arr: any, data: any) => {
  arr.length > 0 &&
    arr.map((child: any) => {
      data.length > 0 &&
        data.map((option: any) => {
          if (option.childrenList.length > 0) {
            for (let i = 0, len = option.childrenList.length; i < len; i++) {
              let item = option.childrenList[i];
              if (item.coding == child) {
                option.chosedArr.push(item.coding);
                option.checkAll = option.chosedArr.length == option.allArr.length ? true : false;
                option.isIndeterminate = option.chosedArr.length > 0 && option.chosedArr.length < option.allArr.length ? true : false;
                item.checkAll = true;
                item.chosedArr = item.allArr;
                item.isIndeterminate = false;
                item.childrenList.length > 0 && checkTrue(item.childrenList);
              } else {
                item.childrenList.length > 0 && checkChosedId(child, item.childrenList);
              }
            }
          }
        });
    });
};

const checkChosedId = (code: any, data: any) => {
  if (data.length > 0) {
    for (let i = 0, len = data.length; i < len; i++) {
      if (data[i].coding == code) {
        data[i].checkAll = true;
        data[i].chosedArr = data[i].allArr;
        data[i].isIndeterminate = false;
        data[i].childrenList.length > 0 && checkTrue(data[i].childrenList);
        changeParentStatus(areaListData.value, data[i].parentId);
        break;
      }
      if (data[i].childrenList.length > 0) {
        checkChosedId(code, data[i].childrenList);
      }
    }
  }
};

const checkTrue = (arr: any) => {
  if (arr.length > 0) {
    arr.map((item: any) => {
      item.checkAll = true;
      item.chosedArr = item.allArr;
      item.isIndeterminate = false;
      item.childrenList.length > 0 && checkTrue(item.childrenList);
    });
  }
};

const changeParentStatus = (list: any, parentId: any) => {
  list.length > 0 &&
    list.forEach((result: any) => {
      let parentCheckedLength = 0;
      let parentIndeterminateLength = 0;
      if (result.coding === parentId) {
        result.chosedArr = [];
        result.childrenList.forEach((item: any) => {
          if (item.isIndeterminate) {
            parentIndeterminateLength++;
          } else if (item.checkAll) {
            parentCheckedLength++;
            result.chosedArr.push(item.coding);
          }
        });
        result.checkAll = parentCheckedLength === result.allArr.length;
        result.isIndeterminate = (parentIndeterminateLength > 0 || parentCheckedLength > 0) && parentCheckedLength < result.allArr.length;
        if (result.parentId !== 0) {
          changeParentStatus(areaListData.value, result.parentId);
        }
      } else if (result.childrenList.length > 0) {
        result.childrenList.length > 0 && changeParentStatus(result.childrenList, parentId);
      }
    });
};

// const dialogVisible = ref(false);
const popWindow = ref();
const titleType = ref(3);

const openCityDialog = (level: number) => {
  // dialogVisible.value = true;
  titleType.value = level;
  popWindow.value.open();
  areaListData.value = [];
  areaListData.value = dataChange(JSON.parse(JSON.stringify(areaData)), 0);
  if (Props.defaultItem.length > 0) {
    checkChosedData(Props.defaultItem, areaListData.value);
  }
}

defineExpose({ openCityDialog })
</script>

<style lang="scss" scoped>
.contentr {
  background: #fff;
}

.regionBox {
  display: flex;
  flex-direction: column;
}

.regionBox :deep(.el-checkbox) {
  margin-right: 0;
}

.btnHidden {
  position: relative;
  width: 16px;
  height: 16px;
  font-size: 14px;
  margin-right: 25px;
  cursor: pointer;
}

.townBox :deep(.el-checkbox) {
  margin-right: 30px;
}
</style>